<?php
/**
 * Created by PhpStorm.
 * User: idcu
 * Date: 2016/3/9
 * Time: 19:31
 */
namespace Admin\Model;
use IDCU\Model\RelationModel;

class CrmUserModel extends RelationModel
{
    protected $tableName = 'user';

    protected $_link = array(
        'Role' => array(
            'mapping_type'          => self::MANY_TO_MANY,
            'class_name'            => 'Role',
            'mapping_name'          => 'role',
            'foreign_key'           => 'user_id',
            'relation_foreign_key'  => 'role_id',
            'relation_table'        => 'zh_role_user',

        ),
        'OaUser' => array(
            'mapping_type'          => self::HAS_MANY,
            'class_name'            => 'OaUser',
            'mapping_name'          => 'oaUser',
            'foreign_key'           => 'crm_id',
        )
    );

    public function addUser($model){

        $role_user_db = D("RoleUser");
        if($model['id']){
            $uid = $model['id'];
            $this->data($model)->save();
        }else{
            $uid = $this->data($model)->add();
        }
        $role_user_db->where(array('user_id' => $uid))->delete();
        $role_id = I("post.role_id",0,"intval");

        //此处一个用户只有一个角色
        if($role_id){
            $role_user_db->data(array('user_id' => $uid,'role_id',$role_id))->add();
        }
    }
    public function _before_write(&$data)
    {
        parent::_before_write($data); // TODO: Change the autogenerated stub
        if($data['password']){
            $data['password']=md5($data['password']);
        }
        if($data['id']) {
            $role_user_db = D("RoleUser");
            $role_user_db->where(array('user_id' => $data['id']))->delete();
            $role_id = I("post.role_id");
            if($role_id){
                $role_user_db->data(array('user_id' => $data['id'],'role_id' => $role_id))->add();
            }
        }


        //此处一个用户只有一个角色
        if($role_id){
            $role_user_db->data(array('user_id' => $uid,'role_id',$role_id))->add();
        }
    }
}